import './style.scss'
import config from '../config'
import {promises} from './service/images'
import straw from "./canvas/straw"
import wall from "./canvas/wall"
import water from "./canvas/water"
import steels from "./canvas/steels"
import enemy from "./canvas/enemy"
import bullet from "./canvas/bullet"
import boss from "./canvas/boss"
import play from "./canvas/player"
import audio from "./service/audio"
import coverImg from './static/images/cover/cover.png'

const app = document.querySelector<HTMLDivElement>('#app')!
// 从配置文件中获取画布尺寸
app.style.width = config.canvas.width + 10 + 'px'
app.style.height = config.canvas.height + 10 + 'px'

export default {
  isStart: false,
  gameState: 'start',
  interval: 0,
  async bootstrap() {
    // 设置app的封面图片
    app.style.backgroundImage = `url(${coverImg})`

    app.addEventListener('click', () => {
      this.start()
      // 判断游戏是否结束
      // @ts-ignore
      this.interval = setInterval(() => {
        if (enemy.models.length === 0) {
          // this.gameState = 'win'
          // this.stop()
        } else if (play.models.length <= 0 || boss.models.length <= 0) {
          this.gameState = 'lose'
          this.stop()
        }
      },500)
    })

  },
  async start() {
    if (!this.isStart) {
      this.isStart = true
      // 开始声音
      await audio.start()
      // 去除app的背景图
      app.style.backgroundImage = 'none'
      // 加载贴图
      await Promise.all(promises)
      // 渲染静态画布
      straw.render()  // 草地
      wall.render()   // 墙
      water.render()  // 水
      steels.render() // 白墙
      // 渲染敌方坦克
      enemy.render()
      // 渲染子弹
      bullet.render()
      boss.render()
      play.render()
    }
  },
  async stop() {
    // 去除定时器
    clearInterval(this.interval)
    console.log('游戏结束')
    // 子弹 坦克 (玩家停止)
    bullet.stop()
    enemy.stop()
    // 提示文字
    this.end()
  },
  end() {
    // 游戏结束提示文字
    let text = this.gameState === 'win' ? '恭喜你，通关了！' : '游戏结束'
    let el = document.createElement('canvas')
    el.width = config.canvas.width
    el.height = config.canvas.height
    let ctx = el.getContext('2d')!
    ctx.font = 'bold 50px sans-serif'
    ctx.fillStyle = 'red'
    ctx.textAlign = 'center'
    ctx.textBaseline = 'middle'
    ctx.fillText(text, config.canvas.width / 2, config.canvas.height / 2)
    app.appendChild(el)
  }
}
